package com.xhs.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhs.model.User;
import com.xhs.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 用户数据库操作Manager
 * 统一管理所有用户相关的数据库操作，包括Cookie
 *
 * @author xhs
 */
@Slf4j
@Service
public class UserManager extends ServiceImpl<UserMapper, User> {

    /**
     * 根据手机号查询用户
     *
     * @param phoneNumber 手机号
     * @return 用户信息
     */
    public User findByPhoneNumber(String phoneNumber) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhoneNumber, phoneNumber)
                .eq(User::getDeleted, 0);
        return this.getOne(queryWrapper);
    }

    /**
     * 保存用户Cookie（字符串格式）
     *
     * @param phoneNumber 手机号
     * @param cookieString Cookie字符串
     * @return 是否成功
     */
    public boolean saveCookie(String phoneNumber, String cookieString) {
        User user = findByPhoneNumber(phoneNumber);
        if (user == null) {
            log.error("用户不存在，无法保存Cookie: phoneNumber={}", phoneNumber);
            return false;
        }

        user.setCookie(cookieString);
        boolean success = this.updateById(user);
        
        if (success) {
            log.info("Cookie已保存到数据库: phoneNumber={}, cookieLength={}", phoneNumber, 
                    cookieString != null ? cookieString.length() : 0);
        } else {
            log.error("保存Cookie失败: phoneNumber={}", phoneNumber);
        }
        
        return success;
    }

    /**
     * 获取用户Cookie字符串
     *
     * @param phoneNumber 手机号
     * @return Cookie字符串
     */
    public String getCookie(String phoneNumber) {
        User user = findByPhoneNumber(phoneNumber);
        if (user == null) {
            log.warn("用户不存在: phoneNumber={}", phoneNumber);
            return null;
        }
        
        String cookieString = user.getCookie();
        if (cookieString == null || cookieString.trim().isEmpty()) {
            log.warn("用户无Cookie: phoneNumber={}", phoneNumber);
            return null;
        }

        log.info("从数据库获取Cookie成功: phoneNumber={}, cookieLength={}", phoneNumber, cookieString.length());
        return cookieString.trim();
    }

    /**
     * 删除用户Cookie
     *
     * @param phoneNumber 手机号
     * @return 是否成功
     */
    public boolean deleteCookie(String phoneNumber) {
        User user = findByPhoneNumber(phoneNumber);
        if (user == null) {
            log.warn("用户不存在，无法删除Cookie: phoneNumber={}", phoneNumber);
            return false;
        }

        user.setCookie(null);
        boolean success = this.updateById(user);
        
        if (success) {
            log.info("Cookie已删除: phoneNumber={}", phoneNumber);
        } else {
            log.error("删除Cookie失败: phoneNumber={}", phoneNumber);
        }
        
        return success;
    }

    /**
     * 检查用户是否有Cookie
     *
     * @param phoneNumber 手机号
     * @return 是否存在Cookie
     */
    public boolean hasCookie(String phoneNumber) {
        User user = findByPhoneNumber(phoneNumber);
        if (user == null) {
            return false;
        }

        boolean exists = user.getCookie() != null && !user.getCookie().trim().isEmpty();
        log.debug("检查Cookie是否存在: phoneNumber={}, exists={}", phoneNumber, exists);
        return exists;
    }

    /**
     * 保存或更新用户登录信息
     *
     * @param phoneNumber 手机号
     * @param cookieString Cookie字符串（可以为null，表示不更新cookie）
     * @return 用户信息
     */
    public User saveOrUpdateUserLogin(String phoneNumber, String cookieString) {
        User existUser = findByPhoneNumber(phoneNumber);
        
        if (existUser == null) {
            // 新用户
            User newUser = new User();
            newUser.setPhoneNumber(phoneNumber);
            if (cookieString != null) {
                newUser.setCookie(cookieString);
            }
            newUser.setLoginStatus(1);
            newUser.setCreateTime(LocalDateTime.now());
            newUser.setUpdateTime(LocalDateTime.now());
            newUser.setDeleted(0);
            this.save(newUser);
            
            log.info("新用户创建成功: phoneNumber={}, hasCookie={}", phoneNumber, cookieString != null);
            return newUser;
        } else {
            // 更新现有用户
            LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(User::getPhoneNumber, phoneNumber)
                    .set(User::getLoginStatus, 1)
                    .set(User::getUpdateTime, LocalDateTime.now());
            
            // 只有当cookieString不为null时才更新cookie字段
            if (cookieString != null) {
                updateWrapper.set(User::getCookie, cookieString);
                existUser.setCookie(cookieString);
            }
            
            this.update(updateWrapper);
            
            // 返回更新后的用户信息
            existUser.setLoginStatus(1);
            existUser.setUpdateTime(LocalDateTime.now());
            
            log.info("用户信息更新成功: phoneNumber={}, updateCookie={}", phoneNumber, cookieString != null);
            return existUser;
        }
    }

    /**
     * 更新用户登录状态
     *
     * @param phoneNumber 手机号
     * @param loginStatus 登录状态
     */
    public void updateLoginStatus(String phoneNumber, Integer loginStatus) {
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getPhoneNumber, phoneNumber)
                .set(User::getLoginStatus, loginStatus)
                .set(User::getUpdateTime, LocalDateTime.now());
        this.update(updateWrapper);
        
        log.info("用户登录状态更新: phoneNumber={}, loginStatus={}", phoneNumber, loginStatus);
    }
} 